#request爬取有道信息

import re,time,random,hashlib,json
import requests

def salt_sign(keyword):#获取salt,sign码
        now_time = int(time.time()*1000)
        salt = now_time+random.randint(1,10)
        sign = "fanyideskweb" + keyword + str(salt) + "aNPG!!u6sesA>hBAW1@(-"
        sign = hashlib.md5(sign.encode('utf-8')).hexdigest()
        return (salt,sign,now_time)

def getPage(url,keyword):
	try:
		salt,sign,now_time = salt_sign(keyword)
		data = {'i':keyword,
            'rom':'AUTO',
            'to':'AUTO',
            'smartresult':'dict',
            'salt': salt,
			'sign': sign,
            'client':'fanyideskweb',
            'doctype':'json',
            'version':'2.1',
            'keyfrom':'fanyi.web',
            'action':'FY_BY_REALTIME',
            'typoResult':'false'}
		headers={
            'Referer':'http://fanyi.youdao.com/',
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36',
            'Cookie':'OUTFOX_SEARCH_USER_ID=-436151303@10.169.0.83; JSESSIONID=aaajO50X4odGG5auUeLpw; OUTFOX_SEARCH_USER_ID_NCOO=806738224.8182715; fanyi-ad-id=44881; fanyi-ad-closed=1; Hm_lvt_4e5bdf78b2b9fcb88736fc67709f2806=1528556613,1528556720,1528557273; Hm_lpvt_4e5bdf78b2b9fcb88736fc67709f2806=1528557273; Hm_lvt_cc903faaed69cca18f7cf0997b2e62c9=1528556613,1528556720,1528557273; Hm_lpvt_cc903faaed69cca18f7cf0997b2e62c9=1528557273; ___rl__test__cookies'+str(now_time),
		}

		req=requests.post(url,headers=headers,data=data)
		status=req.status_code
		if status == 200:
			content =req.content.decode('utf-8')
			content =json.loads(content)
			data=content['translateResult'][0][0]
			return data['src']+':'+data['tgt']
		else:
			return None
	except Exception as e:
		print('--error--:',str(e))
		return None




if __name__ == '__main__':
	url='http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
	while True:
		keyword=input('\n请输入需要翻译的内容：\n')
		if keyword == 'Q' or keyword == 'q':
			print('翻译结束！')
			break
		content=getPage(url,keyword)
		print('翻译结果:\n',content,'\n')

